//
//  IJKPlayerViewController.m
//  ijkPlayer
//
//  Created by apple on 2018/5/20.
//  Copyright © 2018年 锦. All rights reserved.
//

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define kStatusHeight   [[UIApplication sharedApplication]statusBarFrame].size.height
#import "IJKPlayerViewController.h"
#import "IJKPlayVideoView.h"
#import "VideoCommandView.h"
#import "CollectionViewCell.h"
#import "UIDevice+JWDevice.h"
//#include "libimg2webp.h"
#import "UIView+Toast.h"
#import "TestViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>
#import "NavigationViewController.h"

@interface IJKPlayerViewController ()<VideoCommandViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
/**
 播放器显示view
 */
@property (nonatomic, strong) IJKPlayVideoView  *ijkPlayerView;
/**
 添加播放器View的BGView
 */
@property (nonatomic, strong) UIView *ijkPlayerBGView;
/**
 截图view
 */
@property (nonatomic, strong) UIImageView *snapshotImageView;
/**
 gifView
 */
@property (nonatomic, strong) UIImageView *animationImageView;
/**
 gifBGView
 */
@property (nonatomic, strong) UIView *animationBackgroundView;
/**
 计时View
 */
@property (nonatomic, strong) UIView *timeView;
@property (nonatomic, strong) UILabel *timeLabel;
/**
 视频控制View
 */
@property (strong, nonatomic) VideoCommandView *videoCommandView;

@property (nonatomic, strong) UICollectionView *collectionView;
/**
 记录点击过的cell
 */
@property (assign, nonatomic) NSInteger lastIndex;
@property (strong, nonatomic) NSMutableArray *selectedArr;
/**
 刷新定时器
 */
@property (nonatomic, strong) NSTimer *sliderTimer;
@property (nonatomic,assign) CGRect oldFrame;
/**
 *  是否横屏，默认NO -> 竖屏
 */
@property (nonatomic, assign) BOOL isLandscape;

@property (nonatomic, strong) UIButton *testBtn;

@end

@implementation IJKPlayerViewController
{
    /** 测试视频 */
    NSArray     *_videoPathArr;
    NSArray     *_videoNameArr;
    NSMutableArray  *_timeArr;
    NSMutableArray  *_totalTimeArr;
    /** 判断第一次开启播放器后暂停播放器 */
    BOOL _isNotFirst;
    CGFloat _statusY;
    BOOL _gifbtn;
    
    /** gif图片数组 */
    NSMutableArray *_gifArr;
    CGFloat _gifTime;
    BOOL _isVideoNew;
    /** 进度条是否在拖动 */
    BOOL _isDragging;
    NSTimer *_testTimer;
    CGFloat _testTime;
    BOOL _isTest;
    NSTimeInterval _prepareTimestamp;
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
    [self.ijkPlayerView prepareToPlay];
    [self.ijkPlayerView installMovieNotificationObservers];
}
- (void)viewDidDisappear:(BOOL)animated {
    [_sliderTimer invalidate];
    _sliderTimer = nil;
    [self.ijkPlayerView removeMovieNotificationObservers];
    [self.ijkPlayerView shutdown];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NavigationViewController *navi = (NavigationViewController*)self.navigationController;
    navi._supportLandscape = YES;
    
    _testTime = 0;
    self.lastIndex = -1;
    _isVideoNew = YES;
    [self testData];
    
    _gifArr = [NSMutableArray array];
    
    CGFloat y ;
    BOOL IphoneX = (CGSizeEqualToSize(CGSizeMake(375.f, 812.f), [UIScreen mainScreen].bounds.size) || CGSizeEqualToSize(CGSizeMake(812.f, 375.f), [UIScreen mainScreen].bounds.size));
    if (IphoneX) {
        y = 30;
    }else{
        y = 0;
    }
    _statusY = y;
    /**
     播放器View
     */
    self.ijkPlayerView = [[IJKPlayVideoView alloc]initWithFrame:CGRectMake(0, y, SCREEN_WIDTH, SCREEN_WIDTH * 9 / 16)];
    self.ijkPlayerView.backgroundColor = [UIColor blackColor];
   // self.ijkPlayerView.urlStr = [[NSBundle mainBundle]pathForResource:@"IMG_0541.mp4" ofType:nil];//_videoPathArr[0];
    [self.view addSubview:self.ijkPlayerView];
    
    
    /**
     预先开启播放器，后面会由通知暂停
     */
   // self.ijkPlayerView.urlStr = [[NSBundle mainBundle]pathForResource:@"IMG_0541.mp4" ofType:nil];
    
    
    
    [self.ijkPlayerView addSubview:self.videoCommandView];
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
    
    /**  常用通知
     IJKMPMoviePlayerLoadStateDidChangeNotification  加载状态改变通知
     IJKMPMoviePlayerPlaybackDidFinishNotification   播放结束通知
     IJKMPMoviePlayerPlaybackStateDidChangeNotification 播放状态改变通知
     */
    //  1. 添加播放状态改变的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackStateDidChange:) name:IJKMPMoviePlayerPlaybackStateDidChangeNotification object:nil];
   // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieFirstVideoFrameRendered:) name:IJKMPMoviePlayerFirstVideoFrameRenderedNotification object:nil];
    
    
    self.sliderTimer = [NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(updateSliderUI) userInfo:nil repeats:YES];
    
    
    [self addDetailsCollectionView];
    

}
- (void)movieFirstVideoFrameRendered:(NSNotification*)notification
{

    if (_isTest) {
        
        NSTimeInterval t1 = [[NSDate date] timeIntervalSince1970];
        NSLog(@"PERF:movieFirstVideoFrameRendered111 %f\n", t1-_prepareTimestamp);
        NSMutableArray *arr = _timeArr[_lastIndex];
        CGFloat time = t1-_prepareTimestamp;
        [arr addObject:[NSNumber numberWithFloat:time]];
        
        NSNumber *n = _totalTimeArr[_lastIndex];
        CGFloat t = n.floatValue;
        t += time;
        _totalTimeArr[_lastIndex] = [NSNumber numberWithFloat:t];
        
        _isTest = NO;

        [self.collectionView reloadData];
    }
}


- (void) clearCachesForVideo {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString * p = [NSString stringWithFormat:@"%@/cache/", documentsDir];
    
    
        [self removeFile:p];
    [self.view makeToast:@"已清除缓存" duration:2.0f position:CSToastPositionCenter];
}
- (void)removeFile:(NSString*) path{
    
    BOOL isDir;
    
    [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir];
    
    if (isDir) {
        NSArray* files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
        for (NSString* file in files) {
            [self removeFile:[path stringByAppendingPathComponent:file]];
        }
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
    }
    else{
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
    }
}
- (void)getInternetface {
    
    long long hehe = [self getInterfaceBytes];
    
    
    
    NSLog(@"hehe:%lld",hehe);
    
}



/*获取网络流量信息*/

- (long long)getInterfaceBytes

{
    
    struct ifaddrs *ifa_list = 0, *ifa;
    
    if (getifaddrs(&ifa_list) == -1)
        
    {
        
        return 0;
        
    }
    
    
    
    uint32_t iBytes = 0;
    
    uint32_t oBytes = 0;
    
    
    
    for (ifa = ifa_list; ifa; ifa = ifa->ifa_next)
        
    {
        
        if (AF_LINK != ifa->ifa_addr->sa_family)
            
            continue;
        
        
        
        if (!(ifa->ifa_flags & IFF_UP) && !(ifa->ifa_flags & IFF_RUNNING))
            
            continue;
        
        
        
        if (ifa->ifa_data == 0)
            
            continue;
        
        
        
        /* Not a loopback device. */
        
        if (strncmp(ifa->ifa_name, "lo", 2))
            
        {
            
            struct if_data *if_data = (struct if_data *)ifa->ifa_data;
            
            
            
            iBytes += if_data->ifi_ibytes;
            
            oBytes += if_data->ifi_obytes;
            
        }
        
    }
    
    freeifaddrs(ifa_list);
    
    
    
    NSLog(@"\n[getInterfaceBytes-Total]%d,%d",iBytes,oBytes);
    
    return iBytes + oBytes;
    
}

- (VideoCommandView *)videoCommandView {
    if (!_videoCommandView) {
        
        _videoCommandView = [[[NSBundle mainBundle]loadNibNamed:@"VideoCommandView" owner:nil options:nil]lastObject];
        _videoCommandView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width *9/16);
        _videoCommandView.commandDelegate = self;
        
    }
    return _videoCommandView;
}


/**
 通知
 */
- (void)deviceOrientationDidChange {
    
    
    switch ([[UIApplication sharedApplication] statusBarOrientation] ) {
        case UIInterfaceOrientationPortrait:
            {
                self.ijkPlayerView.frame = CGRectMake(0, _statusY, self.view.frame.size.width, self.view.frame.size.width * 9 / 16);
                self.ijkPlayerView.ijkPlayVideoState = ijkVideo_small;
                self.animationBackgroundView.hidden = YES;
                self.videoCommandView._isFullScreen = NO;
            }
            break;
            
        case UIInterfaceOrientationLandscapeLeft:
            {
                self.ijkPlayerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
                self.ijkPlayerView.ijkPlayVideoState = ijkVideo_fullScreen;
                if (![self.ijkPlayerView.player isPlaying]) {
                    [self.ijkPlayerView.player play];
                }
                self.videoCommandView._isFullScreen = YES;
            }
            break;
        case UIInterfaceOrientationLandscapeRight:
        {
            self.ijkPlayerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
            self.ijkPlayerView.ijkPlayVideoState = ijkVideo_fullScreen;
            if (![self.ijkPlayerView.player isPlaying]) {
                [self.ijkPlayerView.player play];
            }
            self.videoCommandView._isFullScreen = YES;
        }
            break;
        default:
            break;
    }
}
- (void) playbackStateDidChange:(NSNotification *) notification {
    
    //    NSLog(@"%@",notification);
    //    IJKMPMoviePlaybackStateStopped,        停止
    //    IJKMPMoviePlaybackStatePlaying,        正在播放
    //    IJKMPMoviePlaybackStatePaused,         暂停
    //    IJKMPMoviePlaybackStateInterrupted,    打断
    //    IJKMPMoviePlaybackStateSeekingForward, 快进
    //    IJKMPMoviePlaybackStateSeekingBackward 快退
    
    
    switch (self.ijkPlayerView.player.playbackState) {
        case IJKMPMoviePlaybackStateStopped:
            NSLog(@"停止");
            if (_gifbtn) {
                    _gifbtn = NO;
                    [self showAnimationView];
                    [self.videoCommandView setGifButtonSelectState:NO];
                
            }
            break;
        case IJKMPMoviePlaybackStatePlaying:
            NSLog(@"正在播放");
            
            
            break;
        case IJKMPMoviePlaybackStatePaused:
            NSLog(@"暂停");
            break;
        case IJKMPMoviePlaybackStateInterrupted:
            NSLog(@"打断");
            break;
        case IJKMPMoviePlaybackStateSeekingForward:
            NSLog(@"快进");
            break;
        case IJKMPMoviePlaybackStateSeekingBackward:
            NSLog(@"快退");
            break;
        default:
            break;
    }
}


-(void)sliderTimerPause {
    [self.sliderTimer setFireDate:[NSDate distantFuture]];
}
-(void)sliderTimerContinue {
    //启动定时器
    [self.sliderTimer setFireDate:[NSDate distantPast]];
    
    if (self.sliderTimer == nil) {
        self.sliderTimer = [NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(updateSliderUI) userInfo:nil repeats:YES];
    }
}
#pragma mark - 更新进度条
- (void)updateSliderUI {
    //[self getInternetface];
    if (self.ijkPlayerView.player == nil || _isDragging) {
        return;
    }
    
    if (_gifbtn) {
        _gifTime += 0.2;
        UIImage *img = [self.ijkPlayerView thumbnailImageAtCurrentTime];;
        [_gifArr addObject:img];
        if (_gifTime >= 10) {
            [self showAnimationView];
            [self.videoCommandView setGifButtonSelectState:NO];
        }
    }
    
    //总时长
    NSTimeInterval duration = [self.ijkPlayerView duration];
    NSInteger intDuration = duration + 0.5;
    
    if (duration <= 0) {
        return;
    }
    if (_isVideoNew && duration) {
        [self.videoCommandView setVideoTotalTime:intDuration];
        [self.videoCommandView setPointWithSlider:nil];
        _isVideoNew = NO;
    }
    
    
    // position
    NSTimeInterval position;
    if (self.videoCommandView.isMediaSliderBeingDragged) {
        position = self.videoCommandView.videoSlider.value;
    } else {
        position = [self.ijkPlayerView currentTime];
    }
    NSInteger intPosition = position + 0.7;
    if (intDuration > 0) {
        self.videoCommandView.videoSlider.value = position;
    } else {
        self.videoCommandView.videoSlider.value = 0.0f;
    }
    [self.videoCommandView refreshSliderValueWithTime:intPosition];
    
    
    
    // status
    BOOL isPlaying = [self.ijkPlayerView isPlaying];
    [self.videoCommandView setPlayButtonState:isPlaying];
    
    
    
}



#pragma mark    ======== VideoCommandViewDelegate ========
- (BOOL)VideoCommandViewPlayButtonClicked {
    if ([self.ijkPlayerView isPlaying]) {
        [self.ijkPlayerView pause];
        
        return NO;
    }else {
        [self.ijkPlayerView play];
        
        return YES;
    }
}
- (void)VideoCommandViewChangeFrameButtonClicked {
    if (self.ijkPlayerView.ijkPlayVideoState == ijkVideo_fullScreen) {
        [UIDevice setOrientation:UIInterfaceOrientationPortrait];
        self.ijkPlayerView.frame = CGRectMake(0, _statusY, SCREEN_WIDTH, SCREEN_WIDTH * 9 /16);
        self.ijkPlayerView.ijkPlayVideoState = ijkVideo_small;
        self.videoCommandView._isFullScreen = NO;
        return;
    }
    if (self.ijkPlayerView.ijkPlayVideoState == ijkVideo_small) {
        [UIDevice setOrientation:UIInterfaceOrientationLandscapeRight];
        self.ijkPlayerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        self.ijkPlayerView.ijkPlayVideoState = ijkVideo_fullScreen;
        self.videoCommandView._isFullScreen = YES;
        return;
        
        
    }
}
- (void)VideoCommandViewSliderDragingWithTime:(CGFloat)time {
    _isDragging = YES;
  //  [self.ijkPlayerView seekTo:time];
    if ([self.ijkPlayerView isPlaying]) {
        //[self sliderTimerPause];
    }
}
- (void)VideoCommandViewSliderDragEndWithTime:(CGFloat)time {
    _isDragging = NO;
    [self.ijkPlayerView seekTo:time];
    if ([self.ijkPlayerView isPlaying]) {
        //  [self sliderTimerContinue];
    }
    
}
- (void)VideoCommandViewSetRate:(CGFloat)rate {
    [self.ijkPlayerView setCurrentPlaybackRate:rate];
}
- (void)VideoCommandViewWithVideoTime:(CGFloat)time {
    [self.ijkPlayerView seekTo:time];
}
- (void)VideoCommandViewscreenshotClicked {

    UIImage *image = [self.ijkPlayerView thumbnailImageAtCurrentTime];
    
    self.snapshotImageView.image = image;
    self.snapshotImageView.hidden = NO;
    
    
    
    [self performSelector:@selector(imageViewRemove) withObject:nil afterDelay:1];
    
}
- (UIImageView *)snapshotImageView {
    if (!_snapshotImageView) {
        _snapshotImageView = [[UIImageView alloc]initWithFrame:CGRectMake(30, 20, 160, 90)];
        _snapshotImageView.layer.borderWidth = 1;
        _snapshotImageView.layer.borderColor = [UIColor whiteColor].CGColor;
        [self.ijkPlayerView addSubview:self.snapshotImageView];
    }
    return _snapshotImageView;
}
- (void)imageViewRemove {
    self.snapshotImageView.hidden = YES;
    
}


- (void)imageAnimationViewRemove {
    [self.animationImageView stopAnimating];
    self.animationImageView.hidden = YES;
}
- (void)showAnimationView {
    _gifbtn = NO;
    [self creatGifWithImages:_gifArr];
    self.timeLabel.hidden = YES;
    self.animationImageView.animationImages = _gifArr;
    self.animationImageView.hidden = NO;
    self.animationBackgroundView.hidden = NO;
    self.animationImageView.animationRepeatCount = 99;
    self.animationImageView.animationDuration = _gifTime;
    [self.animationImageView startAnimating];
    // [self performSelector:@selector(imageAnimationViewRemove) withObject:nil afterDelay:3];
    
    [self.ijkPlayerView pause];
    
}
- (BOOL)VideoCommandViewGifButtonClicked {
    if (self.ijkPlayerView.ijkPlayVideoState == ijkVideo_small) {
        return NO;
    }
    if (_gifbtn) {
        [self showAnimationView];
        
        return NO;
    }else{
        _gifTime = 0;
        [_gifArr removeAllObjects];
        if (![self.ijkPlayerView isPlaying]) {
            [self.ijkPlayerView play];
        }
        _gifbtn = YES;
        self.timeLabel.hidden = NO;
        
        return YES;
    }
    
    
}
- (UILabel *)timeLabel {
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        _timeLabel.textAlignment = NSTextAlignmentCenter;
        _timeLabel.textColor = [UIColor whiteColor];
        _timeLabel.backgroundColor = [UIColor blackColor];
        _timeLabel.alpha = .7;
        _timeLabel.text = @"开始录制";
        [self.ijkPlayerView addSubview:_timeLabel];
        _timeLabel.hidden = YES;
    }
    return _timeLabel;
}
- (UIImageView *)animationImageView {
    if (!_animationImageView) {
        _animationImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH /2, (SCREEN_WIDTH / 2) * 9 / 16)];
        _animationImageView.layer.borderWidth = 1;
        _animationImageView.layer.borderColor = [UIColor whiteColor].CGColor;
        [self.animationBackgroundView addSubview:self.animationImageView];
        CGPoint center = _animationImageView.center;
        center.x = SCREEN_WIDTH / 2;
        _animationImageView.center = center;
        self.animationImageView.hidden = YES;
    }
    return _animationImageView;
}
- (UIView *)animationBackgroundView {
    if (!_animationBackgroundView) {
        _animationBackgroundView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _animationBackgroundView.backgroundColor = [UIColor clearColor];
        [self.ijkPlayerView addSubview:_animationBackgroundView];
        _animationBackgroundView.hidden = YES;
        
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
        label.text = @"gif图片已生成至(Documents/gif/)下";
        label.textAlignment = NSTextAlignmentCenter;
        [_animationBackgroundView addSubview:label];
        label.backgroundColor = [UIColor blackColor];
        label.textColor = [UIColor whiteColor];
        
        UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 150, 20, 80, 60)];
        [backBtn setTitle:@"取消" forState:UIControlStateNormal];
        [backBtn addTarget:self action:@selector(animationHidden) forControlEvents:UIControlEventTouchUpInside];
        [_animationBackgroundView addSubview:backBtn];
        
    }
    return _animationBackgroundView;
}
- (void)animationHidden {
    self.animationBackgroundView.hidden = YES;
    [self.animationImageView stopAnimating];
    self.animationImageView.image = nil;
    for (int i = (int)_gifArr.count - 1 ; i >= 0; i--) {
        UIImage *img = _gifArr[i];
        [_gifArr removeObject:img];
        img = nil;
    }
    
    
}

- (void)creatGifWithImages:(NSMutableArray *)images {
    //图像目标
    
    CGImageDestinationRef destination;
    //创建输出路径
    
    NSArray *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentStr = [document objectAtIndex:0];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *textDirectory = [documentStr stringByAppendingPathComponent:@"gif"];
    
    [fileManager createDirectoryAtPath:textDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString *path = [textDirectory stringByAppendingPathComponent:@"example.gif"];
    
    //创建CFURL对象
    
    
    
    CFURLRef url = CFURLCreateWithFileSystemPath (
                                                  
                                                  kCFAllocatorDefault,
                                                  
                                                  (CFStringRef)path,
                                                  
                                                  kCFURLPOSIXPathStyle,
                                                  
                                                  false);
    
    
    
    //通过一个url返回图像目标
    destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, images.count, NULL);
    
    
    
    //设置gif的信息,播放间隔时间,基本数据,和delay时间
    
    NSDictionary *frameProperties = [NSDictionary dictionaryWithObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:0.2], (NSString *)kCGImagePropertyGIFDelayTime, nil] forKey:(NSString *)kCGImagePropertyGIFDictionary];
    
    
    
    //设置gif信息
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];
    
    
    
    [dict setObject:[NSNumber numberWithBool:YES] forKey:(NSString*)kCGImagePropertyGIFHasGlobalColorMap];
    
    
    
    [dict setObject:(NSString *)kCGImagePropertyColorModelRGB forKey:(NSString *)kCGImagePropertyColorModel];
    
    
    
    [dict setObject:[NSNumber numberWithInt:8] forKey:(NSString*)kCGImagePropertyDepth];
    
    
    
    [dict setObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount];
    
    NSDictionary *gifProperties = [NSDictionary dictionaryWithObject:dict forKey:(NSString *)kCGImagePropertyGIFDictionary];
    
    //合成gif
    
    for (UIImage* dImg in images)
        
    {
       UIImage *img = [self scaleToSize:dImg size:CGSizeMake(dImg.size.width, dImg.size.height)];
        //UIImage *img = [self imageByScalingAndCroppingForSize:CGSizeMake(dImg.size.width, dImg.size.height) WithSourceImg:dImg];
        CGImageDestinationAddImage(destination, img.CGImage, (__bridge CFDictionaryRef)frameProperties);
        
    }
    
    CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)gifProperties);
    
    CGImageDestinationFinalize(destination);
    
    CFRelease(destination);
    
}
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize WithSourceImg:(UIImage *)sourceImg;
{
    UIImage *sourceImage = sourceImg;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

#pragma mark    ======== UICollectionView ========

- (void)addDetailsCollectionView {
    //collectionView
    UICollectionViewFlowLayout* layout2 = [[UICollectionViewFlowLayout alloc] init];
    float width = self.view.frame.size.width;
    float height = width * 23 / 72;
    layout2.itemSize = CGSizeMake(width, height);
    
    
    //设置分区的头视图和尾视图是否始终固定在屏幕上边和下边
    //    layout2.sectionFootersPinToVisibleBounds = YES;
    //    layout2.sectionHeadersPinToVisibleBounds = YES;
    
    
    //竖直滚动
    layout2.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    // 设置额外滚动区域
    layout2.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    // 设置cell间距
    //设置水平间距, 注意点:系统可能会跳转(计算不准确)
    layout2.minimumInteritemSpacing = 0;
    //设置垂直间距
    layout2.minimumLineSpacing = 0;
    
    
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH *9/16 + _statusY, SCREEN_WIDTH, self.view.frame.size.height - SCREEN_WIDTH *9/16 - _statusY) collectionViewLayout:layout2];//self.view.frame.size.width *9/16
    
    //设置背景颜色
    self.collectionView.backgroundColor = [UIColor clearColor];
    
    //    UIGestureRecognizer *gestur = [[UIGestureRecognizer alloc]init];
    //    gestur.delegate=self;
    //    [self.musicCollectionView addGestureRecognizer:gestur];
    
    
    
    // 设置数据源,展示数据
    self.collectionView.dataSource = self;
    //设置代理,监听
    self.collectionView.delegate = self;
    self.collectionView.alwaysBounceVertical = YES;
    
    // 注册cell
    [self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"CollectionViewCell"];
    
    
    /* 设置UICollectionView的属性 */
    //设置滚动条
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    
    //设置是否需要弹簧效果
    self.collectionView.bounces = NO;
    
    [self.view insertSubview:self.collectionView atIndex:0];
}

#pragma mark    ======== UICollectionViewDelegate ========
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

// 告诉系统每组多少个
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _videoPathArr.count;
}

// 告诉系统每个Cell如何显示
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 1.从缓存池中取
    
    static NSString *cellID2 = @"CollectionViewCell";
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID2 forIndexPath:indexPath];
    
    NSArray *arr = _timeArr[indexPath.row];
    
    if (arr.count) {
        NSNumber *n = arr[arr.count - 1];
        CGFloat time = n.floatValue;
        cell.timeLabel.text = [NSString stringWithFormat:@"最后一次加载时长为%.3f,次数%lu",time,(unsigned long)arr.count];
        NSNumber *tn = _totalTimeArr[indexPath.row];
        CGFloat at = tn.floatValue;
        CGFloat mean = at / arr.count;
        
        cell.meanLabel.text = [NSString stringWithFormat:@"平均值为%.3F",mean];
    }else{
        cell.meanLabel.text = @"--:--";
        cell.timeLabel.text = @"--:--";
    }
    cell.testBtn.tag = indexPath.row;
    [cell.testBtn addTarget:self action:@selector(showTestData:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.nameLabel.text = _videoNameArr[indexPath.row];
    if ([self.selectedArr[indexPath.row] isEqualToString:@"1"]) {
        cell.selectedView.hidden = NO;
    }else{
        cell.selectedView.hidden = YES;
    }
    
    return cell;
    
}
- (void)showTestData:(UIButton *)btn {
    NSArray *arr = _timeArr[btn.tag];
    
    if (arr.count) {
        [self.ijkPlayerView pause];
        TestViewController *vc = [TestViewController new];
        vc.testArr = arr;
        NSNumber *tn = _totalTimeArr[btn.tag];
        CGFloat at = tn.floatValue;
        CGFloat mean = at / arr.count;
        
        vc.title = [NSString stringWithFormat:@"共%lu次，平均值为%.3F",arr.count,mean];
        
        
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self.view makeToast:@"没有数据" duration:1.5f position:CSToastPositionCenter];
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.lastIndex == indexPath.row) {
        return;
    }
    
    
    self.selectedArr[indexPath.row] = @"1";
    if (self.lastIndex >= 0) {
        self.selectedArr[self.lastIndex] = @"0";
    }
    
    self.ijkPlayerView.urlStr = _videoPathArr[indexPath.row];
    
    [self.videoCommandView forNewVideo];
    
    self.lastIndex = indexPath.row;
    
    _testTime = 0;
    //_testTimer = [NSTimer timerWithTimeInterval:0.001 target:self selector:@selector(timeForOpenVideo) userInfo:nil repeats:YES];
  //  [[NSRunLoop mainRunLoop] addTimer:_testTimer forMode:NSRunLoopCommonModes];
    _isTest = YES;
    
    _prepareTimestamp = [[NSDate date] timeIntervalSince1970];
    
    [self.collectionView reloadData];
    _isVideoNew = YES;
    
    
}
- (void)timeForOpenVideo {
    _testTime += 0.001;
}

- (void)testData {
    
 // path8    NSPathStore2 *    @"/Users/apple/Library/Developer/CoreSimulator/Devices/BBD01235-0DEC-493E-9363-84FC35B24DD6/data/Containers/Data/Application/176C3E59-B305-4173-AF86-0A870123B9D0/Documents"    0x00007f82ae701c70
//    NSString *path0 = [[NSBundle mainBundle]pathForResource:@"IMG_0541.mp4" ofType:nil];
//    NSString *path1 = [[NSBundle mainBundle]pathForResource:@"IMG_0840.MOV" ofType:nil];
//    NSString *path2 = [[NSBundle mainBundle]pathForResource:@"IMG_0837.mp4" ofType:nil];
//    NSString *path3 = [[NSBundle mainBundle]pathForResource:@"123.mp4" ofType:nil];
//    NSString *path4 = [[NSBundle mainBundle]pathForResource:@"IMG_0541.mp4" ofType:nil];
//    NSString *path5 = [[NSBundle mainBundle]pathForResource:@"IMG_0837.mp4" ofType:nil];
  // NSString *path8 = [NSHomeDirectory( ) stringByAppendingPathComponent:@"Documents"];
                //NSString *path0 = @"http://ugc.dls.migudm.cn/Client/ugc/funshoot/product/2018052115/25220897844771432.mp4?st=bkG9GoGzlZF9vw3ENoWycw&e=1527503408";//http://ugc.dls.migudm.cn/Client/ugc/funshoot/product/2018052115/25220897844771432.mp4?st=bkG9GoGzlZF9vw3ENoWycw&e=1527503408
    
    NSString *path0 = @"http://ugc.strms.migudm.cn/Client/ugc/funshoot/product/test/GTV_20180510_175736_HLS/security_GTV_20180510_175736.m3u8?st=s5LRAnycG-e-Y0E0J2LJfA&e=1531133457";

                NSString *path1 = @"http://ugc.strms.migudm.cn/Client/ugc/funshoot/product/test/GTV_20180510_174839_HLS/security_GTV_20180510_174839.m3u8?st=LL5ri75oBYy-86Ym0rMsWQ&e=1531133409";//http://ugc.strms.migudm.cn/Client/ugc/funshoot/product/test/GTV_20180510_175204_HLS/security_GTV_20180510_175204.m3u8?st=X8j52yyHi9bJCqhce6zd-Q&e=1531133428
                NSString *path2 = @"http://123.206.58.253/test/a.m3u8";
                NSString *path3 = @"http://123.206.58.253/origin/gtv.m3u8";
                NSString *path4 = @"http://ugc.dls.migudm.cn/Client/ugc/funshoot/product/2018060820/26793028152107877.mp4?st=bz8ZPhB9jDkjg2xFHyMkkQ&e=1528860872";
                NSString *path5 = @"http://ugc.strms.migudm.cn/Client/ugc/funshoot/product/test/GTV_20180510_175736_HLS/security_GTV_20180510_175736.m3u8?st=s5LRAnycG-e-Y0E0J2LJfA&e=1531133457";
//    //NSString *path5 = @"http://ozul7qdmu.bkt.clouddn.com/IMG_0837.mp4";
    _videoPathArr = [NSArray arrayWithObjects:path0,path1,path2,path3,path4,path5, nil];
    _videoNameArr = [NSArray arrayWithObjects:@"视频 1",@"视频 2",@"优化后 3",@"优化前 4",@"视频 5",@"视频 6", nil];
    _selectedArr = [NSMutableArray arrayWithObjects:@"0",@"0",@"0",@"0",@"0",@"0", nil];
    
    
    _timeArr = [NSMutableArray array];
    _totalTimeArr = [NSMutableArray array];
    for (int i = 0; i<6; i++) {
        NSMutableArray *arr = [NSMutableArray array];
        [_timeArr addObject:arr];
        
        CGFloat t = 0;
        [_totalTimeArr addObject:[NSNumber numberWithFloat:t]];
    }
    
    
    
    
    
}

- (void)dealloc {
    NSLog(@"dealloc");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
